package com.wxl.common.base

import android.view.View
import androidx.appcompat.app.AppCompatActivity

class Works {

    private var mBuilder: Builder

    private constructor(mBuilder: Builder) {
        this.mBuilder = mBuilder
        postWork()
    }


    private fun postWork() {
        mBuilder.post()
    }


    fun releaseWorks() {
        mBuilder.works.clear()
        mBuilder.wc.clear()
        mBuilder.position = 0
        mBuilder.context = null
    }


    companion object {
        interface OnWorkCallback {
            fun onNextWork(vararg args: Any)
        }
        private val worksCache = HashMap<String,Works>()
    }

    class Builder {
        internal val works = arrayListOf<WorkPresenter>()
        internal var context: AppCompatActivity? = null
        private val mWorkNextImpl = WorkNextImpl()
        internal var position = -1
        internal val wc = HashMap<String, OnDoWorkCallback>()

        constructor(context: AppCompatActivity) {
            this.context = context
        }

        fun <P : WorkPresenter> add(work: Class<P>, rootView: View): Builder {
            works.add(WorkPresenter.getWork(context!!, work, rootView, mWorkNextImpl))
            return this
        }

        fun <P : WorkPresenter> add(work: Class<P>, rootView: View,callback: OnDoWorkCallback): Builder {
            works.add(WorkPresenter.getWork(context!!, work, rootView, mWorkNextImpl))
            wc.put(work.name,callback)
            return this
        }

        fun queue(): Works {
            return Works(this)
        }

        internal fun post(vararg args: Any) {
            if(position >= 0 && position < works.size){
                postFinishCallback(*args)
            }
            position++
            if (works.isNotEmpty() && position < works.size) {
                postStartCallback(*args)
                works[position].onStartDoWork(*args)
            }
        }

        internal fun postStartCallback(vararg args: Any){
            if(wc.containsKey(works[position]::class.java.name)){
                wc[works[position]::class.java.name]?.onWorkStart(*args)
            }
        }

        internal fun postFinishCallback(vararg args: Any){
            if(wc.containsKey(works[position]::class.java.name)){
                wc.remove(works[position]::class.java.name)?.onWorkFinish(*args)
            }
        }

        internal inner class WorkNextImpl : OnWorkCallback {
            override fun onNextWork(vararg args: Any) {
                post(*args)
            }
        }

    }

}